@{
    ViewData["Title"] = "销售订单管理";
}

<style>
    /* 销售订单页面专用样式 - 作用域限制 */
    .sales-order-page {
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        font-family: 'Microsoft YaHei', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        margin: 0;
        padding: 0;
        min-height: 100vh;
    }

    /* 主容器 */
    .sales-order-page .layui-fluid {
        padding: 24px;
        background: transparent;
    }

    /* 卡片样式 */
    .sales-order-page .layui-card {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
        border: 1px solid rgba(255, 255, 255, 0.2);
        overflow: hidden;
        margin-bottom: 24px;
    }

    /* 卡片头部 */
    .sales-order-page .layui-card-header {
        background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
        color: white;
        padding: 24px 32px;
        border-bottom: none;
        position: relative;
        overflow: hidden;
    }

    .sales-order-page .layui-card-header::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(45deg, transparent 30%, rgba(255, 255, 255, 0.1) 50%, transparent 70%);
        animation: shimmer 3s ease-in-out infinite;
    }

    .sales-order-page .layui-card-header h3 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        position: relative;
        z-index: 2;
    }

    /* 卡片内容 */
    .sales-order-page .layui-card-body {
        padding: 32px;
        background: white;
    }

    /* 搜索区域 */
    .sales-order-page .layui-form {
        background: #f8fafc;
        border-radius: 12px;
        padding: 24px;
        margin-bottom: 24px;
        border: 1px solid #e5e7eb;
    }

    .sales-order-page .layui-form-item {
        margin-bottom: 20px;
    }

    .sales-order-page .layui-form-label {
        font-weight: 500;
        color: #374151;
        width: auto;
        padding: 0 0 8px 0;
        font-size: 14px;
    }

    .sales-order-page .layui-input-inline {
        width: auto;
        margin-right: 16px;
    }

    .sales-order-page .layui-input {
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        padding: 12px 16px;
        font-size: 14px;
        transition: all 0.2s ease;
        background: white;
        color: #374151;
        width: 200px;
    }

    .sales-order-page .layui-input:focus {
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        outline: none;
    }

    /* 按钮样式 */
    .sales-order-page .layui-btn {
        border-radius: 8px;
        padding: 10px 20px;
        font-weight: 500;
        font-size: 14px;
        transition: all 0.2s ease;
        border: none;
        text-align: center;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 6px;
        min-width: 100px;
        position: relative;
        overflow: hidden;
        margin-right: 8px;
    }

    .sales-order-page .layui-btn::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
        transition: left 0.3s ease;
    }

    .sales-order-page .layui-btn:hover::before {
        left: 100%;
    }

    .sales-order-page .layui-btn-normal {
        background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
        color: white;
    }

    .sales-order-page .layui-btn-normal:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
    }

    .sales-order-page .layui-btn-warm {
        background: linear-gradient(135deg, #ea580c 0%, #f97316 100%);
        color: white;
    }

    .sales-order-page .layui-btn-warm:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(249, 115, 22, 0.3);
    }

    .sales-order-page .layui-btn-danger {
        background: linear-gradient(135deg, #dc2626 0%, #ef4444 100%);
        color: white;
    }

    .sales-order-page .layui-btn-danger:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
    }

    .sales-order-page .layui-btn-primary {
        background: #f3f4f6;
        color: #374151;
        border: 2px solid #e5e7eb;
    }

    .sales-order-page .layui-btn-primary:hover {
        background: #e5e7eb;
        border-color: #d1d5db;
        transform: translateY(-1px);
    }

    /* 表格样式 */
    .sales-order-page .layui-table {
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        border: 1px solid #e5e7eb;
        width: 100% !important;
        table-layout: auto !important;
    }

    .sales-order-page .layui-table thead tr {
        background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
        color: white;
    }

    .sales-order-page .layui-table thead th {
        border: none;
        padding: 16px 12px;
        font-weight: 600;
        font-size: 14px;
        text-align: center;
    }

    .sales-order-page .layui-table tbody tr {
        transition: all 0.2s ease;
        border-bottom: 1px solid #f3f4f6;
    }

    .sales-order-page .layui-table tbody tr:hover {
        background: #f8fafc;
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .sales-order-page .layui-table tbody td {
        padding: 16px 12px;
        border: none;
        font-size: 14px;
        color: #374151;
        text-align: center;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    /* 分页样式 */
    .sales-order-page .layui-laypage {
        text-align: center;
        margin-top: 24px;
    }

    .sales-order-page .layui-laypage a,
    .sales-order-page .layui-laypage span {
        border-radius: 6px;
        margin: 0 3px;
        transition: all 0.2s ease;
    }

    .sales-order-page .layui-laypage a:hover {
        background-color: #3b82f6;
        color: white;
        transform: translateY(-1px);
    }

    .sales-order-page .layui-laypage .layui-laypage-curr .layui-laypage-em {
        background-color: #3b82f6;
        border-radius: 6px;
    }

    /* 弹框样式 */
    .sales-order-page .layui-layer {
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
        z-index: 19891020 !important;
    }

    .sales-order-page .layui-layer-title {
        background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
        color: white;
        border-bottom: none;
        font-weight: 600;
        padding: 20px 24px;
    }

    .sales-order-page .layui-layer-content {
        padding: 24px;
        background: #f8fafc;
        z-index: 19891021 !important;
        position: relative;
        width: 100% !important;
        max-width: none !important;
    }

    /* 弹框内表单 */
    .sales-order-page .layui-form-item {
        margin-bottom: 20px;
    }

    .sales-order-page .layui-form-label {
        font-weight: 500;
        color: #374151;
        width: 100px;
    }

    .sales-order-page .layui-input-block {
        margin-left: 100px;
    }

    .sales-order-page .layui-input,
    .sales-order-page .layui-select,
    .sales-order-page .layui-textarea {
        border-radius: 8px;
        border: 2px solid #e5e7eb;
        padding: 12px 16px;
        font-size: 14px;
        transition: all 0.2s ease;
    }

    .sales-order-page .layui-input:focus,
    .sales-order-page .layui-select:focus,
    .sales-order-page .layui-textarea:focus {
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }

    /* 弹框内按钮 */
    .sales-order-page .layui-btn {
        border-radius: 8px;
        font-weight: 500;
        padding: 10px 20px;
        font-size: 14px;
        transition: all 0.2s ease;
        border: none;
        text-align: center;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 6px;
        min-height: 40px;
        line-height: 1;
        white-space: nowrap;
    }

    /* 弹框内表格 */
    .sales-order-page .layui-table {
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .sales-order-page .layui-table thead tr {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    }

    .sales-order-page .layui-table tbody tr:hover {
        background-color: #f8f9fa;
    }

    /* 表格容器自适应 */
    .sales-order-page .layui-table-view {
        width: 100% !important;
    }

    .sales-order-page .layui-layer-content .layui-table-view {
        width: 100% !important;
        overflow-x: auto;
    }

    /* 强制列宽自适应 */
    .sales-order-page .layui-table th:not(.layui-table-col-special),
    .sales-order-page .layui-table td:not(.layui-table-col-special) {
        width: auto !important;
        min-width: 80px;
    }

    /* 图标样式 */
    .sales-order-page .layui-icon {
        font-size: 16px;
        line-height: 1;
    }

    /* 动画定义 */
    @@keyframes shimmer {
        0% {
            transform: translateX(-100%) rotate(45deg);
        }

        100% {
            transform: translateX(100%) rotate(45deg);
        }
    }

    /* 响应式设计 */
    @@media (max-width: 768px) {
        .sales-order-page .layui-fluid {
            padding: 16px;
        }

        .layui-card-body {
            padding: 20px;
        }

        .layui-input-inline {
            width: 100%;
            margin-right: 0;
            margin-bottom: 16px;
        }

        .layui-input {
            width: 100%;
        }

        .layui-btn {
            margin-right: 0;
            margin-bottom: 8px;
            justify-content: center;
        }
    }

    /* 确保弹框层级正确 */
    .layui-layer-shade,
    .layui-layer-shade[layui-layer-shade] {
        z-index: 19891010 !important;
    }

    /* 特别针对销售订单弹框 */
    #salesOrderModal {
        z-index: 19891022 !important;
        position: relative;
    }

    /* 特别针对产品选择弹框 */
    #productSelectModal {
        z-index: 19891023 !important;
        position: relative;
    }
</style>



<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <h3>销售订单</h3>
                </div>
                <div class="layui-card-body">
                    <!-- 搜索区域 -->
                    <div class="layui-form layui-form-pane" style="margin-bottom: 10px;">
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">单据编号</label>
                                <div class="layui-input-inline">
                                    <input type="text" id="searchOrderNo" placeholder="请输入单据编号" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <button type="button" class="layui-btn" id="searchBtn"
                                    onclick="searchSalesOrder()">查询</button>
                                <button type="button" class="layui-btn layui-btn-normal" id="newBtn"
                                    onclick="showCreateModal()">+新建</button>
                                <button type="button" class="layui-btn layui-btn-warm" id="editBtn"
                                    onclick="editSelected()">编辑</button>
                                <button type="button" class="layui-btn layui-btn-primary" id="printBtn"
                                    onclick="printSelected()">打印</button>
                                <button type="button" class="layui-btn layui-btn-danger" id="deleteBtn"
                                    onclick="deleteSelected()">删除</button>

                                <button type="button" class="layui-btn layui-btn-primary" id="exportBtn"
                                    onclick="exportData()">导出</button>
                                <button type="button" class="layui-btn layui-btn-primary" id="columnSettingsBtn"
                                    onclick="showColumnSettings()">显示列设置</button>
                            </div>
                        </div>
                    </div>

                    <!-- 销售订单表格 -->
                    <table id="salesOrderTable" lay-filter="salesOrderTable"></table>
                </div>
            </div>
        </div>
    </div>

    <!-- 销售订单产品明细表格 -->
    <div class="layui-row layui-col-space15" style="margin-top: 15px;">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <h3>销售订单-产品明细</h3>
                </div>
                <div class="layui-card-body">
                    <table id="salesOrderProductTable" lay-filter="salesOrderProductTable"></table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 新增/编辑销售订单模态框 -->
<div id="salesOrderModal" style="display: none; padding: 20px;">
    <form class="layui-form" id="salesOrderForm">
        <div class="layui-form-item">
            <label class="layui-form-label">单据编号</label>
            <div class="layui-input-block">
                <input type="text" id="orderNo" name="orderNo" placeholder="请输入,忽略将自动生成" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <textarea id="remark" name="remark" placeholder="请输入备注" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <div
                    style="background-color: #fff3cd; padding: 10px; border-left: 4px solid #ffc107; margin-bottom: 15px;">
                    点击【数量】可以对订单数量直接进行修改
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <h3>销售订单-产品明细</h3>
                <div style="margin-bottom: 10px;">
                    <button type="button" class="layui-btn layui-btn-sm" id="selectProductBtn"
                        onclick="showProductSelectModal()">+选择产品</button>
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="deleteProductRowBtn"
                        onclick="deleteProductRow()">删除行</button>
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="refreshProductBtn"
                        onclick="refreshProductTable()">刷新</button>
                </div>
                <table id="productDetailTable" lay-filter="productDetailTable"></table>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn" id="saveSalesOrderBtn" onclick="saveSalesOrder()">保存</button>
                <button type="button" class="layui-btn layui-btn-primary" id="closeSalesOrderBtn"
                    onclick="closeSalesOrderModal()">关闭</button>
            </div>
        </div>
    </form>
</div>

<!-- 产品选择模态框 -->
<div id="productSelectModal" style="display: none; padding: 20px;">
    <div class="layui-form layui-form-pane" style="margin-bottom: 10px;">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">产品编码</label>
                <div class="layui-input-inline">
                    <input type="text" id="searchProductCode" placeholder="请输入产品编码" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">产品名称</label>
                <div class="layui-input-inline">
                    <input type="text" id="searchProductName" placeholder="请输入产品名称" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <button type="button" class="layui-btn" id="searchProductsBtn" onclick="searchProducts()">搜索</button>
            </div>
        </div>
    </div>
    <table id="productSelectTable" lay-filter="productSelectTable"></table>
    <div style="margin-top: 10px; text-align: center;">
        <button type="button" class="layui-btn" id="addSelectedProductsBtn"
            onclick="addSelectedProducts()">添加选择的数据</button>
        <button type="button" class="layui-btn layui-btn-primary" onclick="closeProductSelectModal()">关闭</button>
    </div>
</div>

<!-- 显示列设置弹窗 -->
<div id="columnSettingsModal" style="display: none;">
    <div class="column-settings-modal">
        <div class="modal-header">
            <h3>显示列设置</h3>
            <p>选择要显示的表格列，拖动可调整顺序</p>
        </div>
        <div class="modal-body">
            <table class="layui-table" id="columnSettingsTable">
                <thead>
                    <tr>
                        <th width="60">#</th>
                        <th>列名</th>
                        <th width="100">是否显示</th>
                    </tr>
                </thead>
                <tbody id="columnSettingsBody">
                    <tr data-field="orderNo" class="draggable-row">
                        <td>1</td>
                        <td class="drag-handle" style="cursor: move;">
                            <i class="layui-icon layui-icon-drag" style="margin-right: 8px; color: #999;"></i>
                            单据编号
                        </td>
                        <td><input type="checkbox" name="orderNo" lay-skin="primary" title="显示" checked></td>
                    </tr>
                    <tr data-field="remark" class="draggable-row">
                        <td>2</td>
                        <td class="drag-handle" style="cursor: move;">
                            <i class="layui-icon layui-icon-drag" style="margin-right: 8px; color: #999;"></i>
                            备注
                        </td>
                        <td><input type="checkbox" name="remark" lay-skin="primary" title="显示" checked></td>
                    </tr>
                    <tr data-field="createTime" class="draggable-row">
                        <td>3</td>
                        <td class="drag-handle" style="cursor: move;">
                            <i class="layui-icon layui-icon-drag" style="margin-right: 8px; color: #999;"></i>
                            创建时间
                        </td>
                        <td><input type="checkbox" name="createTime" lay-skin="primary" title="显示" checked></td>
                    </tr>
                    <tr data-field="creatorName" class="draggable-row">
                        <td>4</td>
                        <td class="drag-handle" style="cursor: move;">
                            <i class="layui-icon layui-icon-drag" style="margin-right: 8px; color: #999;"></i>
                            创建人
                        </td>
                        <td><input type="checkbox" name="creatorName" lay-skin="primary" title="显示" checked></td>
                    </tr>
                    <tr data-field="modifyTime" class="draggable-row">
                        <td>5</td>
                        <td class="drag-handle" style="cursor: move;">
                            <i class="layui-icon layui-icon-drag" style="margin-right: 8px; color: #999;"></i>
                            修改时间
                        </td>
                        <td><input type="checkbox" name="modifyTime" lay-skin="primary" title="显示" checked></td>
                    </tr>
                    <tr data-field="modifierName" class="draggable-row">
                        <td>6</td>
                        <td class="drag-handle" style="cursor: move;">
                            <i class="layui-icon layui-icon-drag" style="margin-right: 8px; color: #999;"></i>
                            修改人
                        </td>
                        <td><input type="checkbox" name="modifierName" lay-skin="primary" title="显示" checked></td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div class="modal-footer">
            <button class="layui-btn layui-btn-primary" id="cancelColumnSettings">取消</button>
            <button class="layui-btn layui-btn-primary" id="resetColumnSettings">重置</button>
            <button class="layui-btn" id="confirmColumnSettings">确定</button>
        </div>
    </div>
</div>

<script type="text/html" id="productDetailTableBar">
    <a class="layui-btn layui-btn-xs" lay-event="editQuantity">编辑数量</a>
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
</script>



<style>
    /* 页面整体样式美化 */
    body {
        background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        font-family: 'Microsoft YaHei', Arial, sans-serif;
    }

    /* 主容器样式 */
    .layui-container {
        padding: 20px;
        min-height: calc(100vh - 120px);
    }

    /* 卡片样式 */
    .layui-card {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
        border-radius: 15px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        border: 1px solid rgba(255, 255, 255, 0.2);
        margin-bottom: 20px;
        overflow: hidden;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }

    .layui-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
    }

    /* 卡片头部样式 */
    .layui-card-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 20px 25px;
        border-bottom: none;
        position: relative;
        overflow: hidden;
    }

    .layui-card-header::before {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.1), transparent);
        transform: rotate(45deg);
        animation: shimmer 3s ease-in-out infinite;
    }

    .layui-card-header h3 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        position: relative;
        z-index: 2;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    /* 卡片内容样式 */
    .layui-card-body {
        padding: 25px;
        background: white;
    }

    /* 搜索区域样式 */
    .layui-form-item {
        margin-bottom: 20px;
    }

    .layui-input {
        border-radius: 8px;
        border: 2px solid #e9ecef;
        padding: 10px 15px;
        transition: all 0.3s ease;
        background: #f8f9fa;
    }

    .layui-input:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        background: white;
    }

    /* 按钮样式美化 */
    .layui-btn {
        border-radius: 8px;
        padding: 8px 20px;
        font-weight: 500;
        transition: all 0.3s ease;
        border: none;
        position: relative;
        overflow: hidden;
        text-align: center;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        min-width: 80px;
    }

    .layui-btn::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
        transition: left 0.5s;
    }

    .layui-btn:hover::before {
        left: 100%;
    }

    .layui-btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    /* 按钮内图标和文字居中 */
    .layui-btn i {
        margin-right: 4px;
        display: inline-block;
        vertical-align: middle;
    }

    .layui-btn span {
        display: inline-block;
        vertical-align: middle;
    }

    /* 不同颜色按钮的渐变效果 */
    .layui-btn-normal {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    .layui-btn-warm {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }

    .layui-btn-danger {
        background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
    }

    .layui-btn-primary {
        background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
        color: white;
    }

    /* 表格样式美化 */
    .layui-table {
        border-radius: 10px;
        overflow: hidden;
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    }

    .layui-table thead tr {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }

    .layui-table thead th {
        border: none;
        padding: 15px 12px;
        font-weight: 600;
        text-align: center;
    }

    .layui-table tbody tr {
        transition: all 0.3s ease;
    }

    .layui-table tbody tr:hover {
        background-color: #f8f9fa;
        transform: scale(1.01);
    }

    .layui-table tbody td {
        padding: 12px;
        border-bottom: 1px solid #f0f0f0;
        text-align: center;
    }

    /* 分页样式 */
    .layui-laypage {
        text-align: center;
        margin-top: 20px;
    }

    .layui-laypage a,
    .layui-laypage span {
        border-radius: 6px;
        margin: 0 3px;
        transition: all 0.3s ease;
    }

    .layui-laypage a:hover {
        background-color: #667eea;
        color: white;
        transform: translateY(-1px);
    }

    .layui-laypage .layui-laypage-curr .layui-laypage-em {
        background-color: #667eea;
        border-radius: 6px;
    }

    /* 模态框样式美化 */
    .layui-layer {
        border-radius: 15px;
        overflow: hidden;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
    }

    .layui-layer-title {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-bottom: none;
        font-weight: 600;
    }

    /* 表单样式 */
    .layui-form-label {
        font-weight: 500;
        color: #333;
    }

    .layui-textarea {
        border-radius: 8px;
        border: 2px solid #e9ecef;
        transition: all 0.3s ease;
    }

    .layui-textarea:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }

    /* 提示信息样式 */
    .layui-layer-msg {
        border-radius: 8px;
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    }

    /* 动画效果 */
    @@keyframes shimmer {
        0% {
            transform: rotate(45deg) translateX(-100%);
        }

        100% {
            transform: rotate(45deg) translateX(100%);
        }
    }

    @@keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(30px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    /* 页面加载动画 */
    .layui-card {
        animation: fadeInUp 0.6s ease-out;
    }

    .layui-card:nth-child(2) {
        animation-delay: 0.1s;
    }

    /* 显示列设置弹窗样式 */
    .column-settings-modal {
        background: white;
        border-radius: 15px;
        overflow: hidden;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
    }

    .column-settings-modal .modal-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 25px;
        text-align: center;
        position: relative;
        overflow: hidden;
    }

    .column-settings-modal .modal-header::before {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.1), transparent);
        transform: rotate(45deg);
        animation: shimmer 3s ease-in-out infinite;
    }

    .column-settings-modal .modal-header h3 {
        margin: 0 0 8px 0;
        font-size: 20px;
        font-weight: 600;
        position: relative;
        z-index: 2;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .column-settings-modal .modal-header p {
        margin: 0;
        font-size: 14px;
        opacity: 0.9;
        position: relative;
        z-index: 2;
    }

    .column-settings-modal .modal-body {
        padding: 25px;
        max-height: 350px;
        overflow-y: auto;
        background: #fafbfc;
    }

    .column-settings-modal .modal-footer {
        padding: 20px 25px;
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        border-top: 1px solid #dee2e6;
        text-align: right;
    }

    .column-settings-modal .modal-footer button {
        margin-left: 12px;
        border-radius: 8px;
        padding: 8px 20px;
        font-weight: 500;
        transition: all 0.3s ease;
        text-align: center;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        min-width: 70px;
    }

    .column-settings-modal .modal-footer button:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .draggable-row {
        transition: all 0.3s ease;
        border-radius: 8px;
        margin-bottom: 5px;
    }

    .draggable-row:hover {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        transform: translateX(5px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .drag-handle {
        cursor: move;
        padding: 8px;
        border-radius: 6px;
        transition: all 0.3s ease;
    }

    .drag-handle:hover {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        transform: scale(1.05);
    }

    .drag-handle i {
        transition: all 0.3s ease;
    }

    .drag-handle:hover i {
        color: white !important;
        transform: rotate(5deg);
    }

    /* 拖拽时的样式 */
    .ui-sortable-helper {
        background: white;
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        border: 2px solid #667eea;
        border-radius: 10px;
        transform: rotate(2deg);
    }

    .ui-sortable-placeholder {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        border: 2px dashed #667eea;
        border-radius: 8px;
        height: 50px;
        margin: 5px 0;
    }

    /* 复选框样式美化 */
    .column-settings-modal input[type="checkbox"] {
        transform: scale(1.2);
        accent-color: #667eea;
    }

    /* 滚动条样式 */
    .column-settings-modal .modal-body::-webkit-scrollbar {
        width: 6px;
    }

    .column-settings-modal .modal-body::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
    }

    .column-settings-modal .modal-body::-webkit-scrollbar-thumb {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 3px;
    }

    .column-settings-modal .modal-body::-webkit-scrollbar-thumb:hover {
        background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
    }

    /* 状态指示器 */
    .status-indicator {
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        margin-right: 8px;
        animation: pulse 2s infinite;
    }

    .status-active {
        background: #00b894;
    }

    .status-inactive {
        background: #d63031;
    }

    @@keyframes pulse {
        0% {
            opacity: 1;
        }

        50% {
            opacity: 0.5;
        }

        100% {
            opacity: 1;
        }
    }

    /* 加载动画 */
    .loading-spinner {
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid #667eea;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-right: 8px;
    }

    @@keyframes spin {
        0% {
            transform: rotate(0deg);
        }

        100% {
            transform: rotate(360deg);
        }
    }

    /* 表格行状态样式 */
    .table-row-new {
        background: linear-gradient(135deg, #e8f5e8 0%, #d4edda 100%);
        border-left: 4px solid #28a745;
    }

    .table-row-modified {
        background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
        border-left: 4px solid #ffc107;
    }

    .table-row-deleted {
        background: linear-gradient(135deg, #f8d7da 0%, #f5c6cb 100%);
        border-left: 4px solid #dc3545;
        opacity: 0.7;
    }

    /* 响应式设计 */
    @@media (max-width: 768px) {
        .layui-container {
            padding: 10px;
        }

        .layui-card-body {
            padding: 15px;
        }

        .layui-btn {
            padding: 6px 15px;
            font-size: 12px;
        }

        .layui-table thead th,
        .layui-table tbody td {
            padding: 8px 6px;
            font-size: 12px;
        }
    }

    /* 深色模式支持 */
    @@media (prefers-color-scheme: dark) {
        body {
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: #ecf0f1;
        }

        .layui-card {
            background: rgba(44, 62, 80, 0.95);
            border: 1px solid rgba(52, 73, 94, 0.3);
        }

        .layui-card-body {
            background: #34495e;
            color: #ecf0f1;
        }

        .layui-input {
            background: #2c3e50;
            border-color: #34495e;
            color: #ecf0f1;
        }

        .layui-input:focus {
            background: #34495e;
            border-color: #667eea;
        }

        .layui-table tbody tr:hover {
            background-color: #2c3e50;
        }
    }
</style>

@section Scripts {
    <!-- 引入jQuery UI库支持拖拽功能 -->
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">

    <script>
        // 防重复点击工具函数
        var buttonClickStates = {};

        function preventDuplicateClick(buttonId, callback, timeout) {
            if (buttonClickStates[buttonId]) {
                return false; // 按钮已被禁用
            }

            // 禁用按钮
            buttonClickStates[buttonId] = true;
            var $button = $('#' + buttonId);
            var originalText = $button.text();
            var originalDisabled = $button.prop('disabled');

            // 设置按钮状态
            $button.prop('disabled', true).text('处理中...');

            try {
                // 执行回调函数
                var result = callback();

                // 设置超时恢复
                setTimeout(function () {
                    if (buttonClickStates[buttonId]) {
                        buttonClickStates[buttonId] = false;
                        $button.prop('disabled', originalDisabled).text(originalText);
                    }
                }, timeout || 3000);

                return result;
            } catch (error) {
                // 如果回调函数执行出错，立即恢复按钮状态
                console.error('按钮操作出错:', error);
                buttonClickStates[buttonId] = false;
                $button.prop('disabled', originalDisabled).text(originalText);
                throw error; // 重新抛出错误
            }
        }

        // 为AJAX请求添加防重复点击
        function ajaxWithPreventDuplicate(buttonId, ajaxOptions, timeout) {
            return preventDuplicateClick(buttonId, function () {
                $.ajax(ajaxOptions);
            }, timeout);
        }

        // 重置所有按钮状态
        function resetAllButtonStates() {
            Object.keys(buttonClickStates).forEach(function (buttonId) {
                buttonClickStates[buttonId] = false;
                var $button = $('#' + buttonId);
                if ($button.length > 0) {
                    $button.prop('disabled', false);
                    // 恢复原始文本
                    var originalTexts = {
                        'searchBtn': '查询',
                        'newBtn': '+新建',
                        'editBtn': '编辑',
                        'printBtn': '打印',
                        'deleteBtn': '删除',
                        'exportBtn': '导出',
                        'columnSettingsBtn': '显示列设置',
                        'selectProductBtn': '+选择产品',
                        'deleteProductRowBtn': '删除行',
                        'refreshProductBtn': '刷新',
                        'saveSalesOrderBtn': '保存',
                        'searchProductsBtn': '搜索',
                        'addSelectedProductsBtn': '添加选择的数据'
                    };
                    $button.text(originalTexts[buttonId] || '按钮');
                }
            });
        }

        // 调试函数：手动重置按钮状态（可在浏览器控制台调用）
        window.resetButtons = function () {
            resetAllButtonStates();
            console.log('所有按钮状态已重置');
        };

        // 调试函数：查看当前按钮状态（可在浏览器控制台调用）
        window.getButtonStates = function () {
            console.log('当前按钮状态:', buttonClickStates);
            return buttonClickStates;
        };

        // 销售订单表格列设置
        var columnSettings = {
            orderNo: { visible: true, order: 1 },
            remark: { visible: true, order: 2 },
            createTime: { visible: true, order: 3 },
            creatorName: { visible: true, order: 4 },
            modifyTime: { visible: true, order: 5 },
            modifierName: { visible: true, order: 6 }
        };

        // 列配置
        var columnConfigs = {
            orderNo: { field: 'orderNo', title: '单据编号', minWidth: 200, templet: function (d) { return '<a href="javascript:;" style="color: #1E9FFF;" lay-event="edit">' + d.orderNo + '</a>'; } },
            remark: { field: 'remark', title: '备注', minWidth: 200 },
            createTime: { field: 'createTime', title: '创建时间', width: 160, templet: function (d) { if (d.createTime) { var date = new Date(d.createTime); return date.getFullYear() + '年' + String(date.getMonth() + 1).padStart(2, '0') + '月' + String(date.getDate()).padStart(2, '0') + '日 ' + String(date.getHours()).padStart(2, '0') + ':' + String(date.getMinutes()).padStart(2, '0') + ':' + String(date.getSeconds()).padStart(2, '0'); } return '-'; } },
            creatorName: { field: 'creatorName', title: '创建人', width: 120 },
            modifyTime: { field: 'modifyTime', title: '修改时间', width: 160, templet: function (d) { if (d.modifyTime) { var date = new Date(d.modifyTime); return date.getFullYear() + '年' + String(date.getMonth() + 1).padStart(2, '0') + '月' + String(date.getDate()).padStart(2, '0') + '日 ' + String(date.getHours()).padStart(2, '0') + ':' + String(date.getMinutes()).padStart(2, '0') + ':' + String(date.getSeconds()).padStart(2, '0'); } return '-'; } },
            modifierName: { field: 'modifierName', title: '修改人', width: 120 }
        };

        layui.use(['table', 'layer', 'form'], function () {
            var table = layui.table;
            var layer = layui.layer;
            var form = layui.form;
            var $ = layui.$ || window.jQuery;

            // 全局AJAX错误处理
            $(document).ajaxError(function (event, xhr, settings, error) {
                console.error('AJAX请求失败:', error);
                // 如果请求失败，重置所有按钮状态
                setTimeout(function () {
                    resetAllButtonStates();
                }, 1000);
            });

            // 销售订单表格
            table.render({
                elem: '#salesOrderTable',
                url: '/SalesOrder/QuerySalesOrder',
                method: 'get',
                where: {
                    pageIndex: 1,
                    pageSize: 10
                },
                parseData: function (res) {
                    return {
                        "code": res.code === 200 ? 0 : 1,
                        "msg": res.msg || res.message,
                        "count": res.data ? res.data.totaCount : 0,
                        "data": res.data ? res.data.pageData : []
                    };
                },
                cols: [getSalesOrderTableCols()],
                page: true,
                limit: 10,
                limits: [10, 20, 30, 50],
                height: 400,
                even: true,
                text: {
                    none: '无数据'
                }
            });

            // 销售订单产品明细表格
            table.render({
                elem: '#salesOrderProductTable',
                url: '/SalesOrder/QuerySalesOrderProduct',
                method: 'get',
                where: {
                    salesOrderId: 0, // 初始为空，点击行时会更新
                    pageIndex: 1,
                    pageSize: 10
                },
                cols: [[
                    { field: 'productCode', title: '产品编号' },
                    { field: 'productName', title: '产品名称' },
                    { field: 'productSpec', title: '产品规格' },
                    { field: 'workOrderNo', title: '工单编号' },
                    { field: 'quantity', title: '数量' },
                    { field: 'completedQuantity', title: '完成数' },
                    {
                        field: 'createTime',
                        title: '创建时间',
                        templet: function (d) {
                            if (d.createTime) {
                                var date = new Date(d.createTime);
                                return date.getFullYear() + '年' +
                                    String(date.getMonth() + 1).padStart(2, '0') + '月' +
                                    String(date.getDate()).padStart(2, '0') + '日 ' +
                                    String(date.getHours()).padStart(2, '0') + ':' +
                                    String(date.getMinutes()).padStart(2, '0') + ':' +
                                    String(date.getSeconds()).padStart(2, '0');
                            }
                            return '';
                        }
                    },
                    { field: 'creatorName', title: '创建人' }
                ]],
                page: true,
                limit: 10,
                limits: [10, 20, 30, 50],
                height: 300,
                even: true,
                text: {
                    none: '无数据'
                },
                parseData: function (res) {
                    return {
                        "code": res.code === 200 ? 0 : 1,
                        "msg": res.msg || res.message,
                        "count": res.data ? res.data.totaCount : 0,
                        "data": res.data ? res.data.pageData : []
                    };
                }
            });

            // 产品明细表格（新增/编辑用）
            table.render({
                elem: '#productDetailTable',
                cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    { field: 'productCode', title: '产品编号' },
                    { field: 'productName', title: '产品名称' },
                    { field: 'productSpec', title: '产品规格' },
                    { field: 'workOrderNo', title: '工单编号' },
                    { field: 'quantity', title: '数量', edit: 'text' },
                    {
                        field: 'createTime',
                        title: '创建时间',
                        templet: function (d) {
                            if (d.createTime) {
                                var date = new Date(d.createTime);
                                return date.getFullYear() + '年' +
                                    String(date.getMonth() + 1).padStart(2, '0') + '月' +
                                    String(date.getDate()).padStart(2, '0') + '日 ' +
                                    String(date.getHours()).padStart(2, '0') + ':' +
                                    String(date.getMinutes()).padStart(2, '0') + ':' +
                                    String(date.getSeconds()).padStart(2, '0');
                            }
                            return '';
                        }
                    },
                    { field: 'creatorName', title: '创建人' }
                ]],
                page: true,
                limit: 10,
                limits: [10, 20, 30, 50],
                height: 300,
                data: [],
                even: true,
                text: {
                    none: '无数据'
                }
            });

            // 产品选择表格
            table.render({
                elem: '#productSelectTable',
                url: '/SalesOrder/GetProductSelect',
                method: 'get',
                where: {
                    pageIndex: 1,
                    pageSize: 30
                },
                error: function (res) {
                    layer.msg('加载产品数据失败: ' + (res.msg || '未知错误'));
                },
                parseData: function (res) {
                    // 如果返回的不是对象，说明有错误
                    if (typeof res !== 'object' || res === null) {
                        return {
                            "code": 1,
                            "msg": "数据格式错误",
                            "count": 0,
                            "data": []
                        };
                    }

                    // 处理不同的数据结构
                    var code = 1;
                    var count = 0;
                    var data = [];

                    // 检查成功状态码
                    if (res.code === 0 || res.code === 200 || res.success === true) {
                        code = 0;
                    }

                    // 尝试多种可能的数据结构
                    if (res.totalCount !== undefined) {
                        count = res.totalCount;
                        data = res.pageData || [];
                    } else if (res.data && res.data.totaCount !== undefined) {
                        count = res.data.totaCount;
                        data = res.data.pageData || [];
                    } else if (res.data && res.data.totalCount !== undefined) {
                        count = res.data.totalCount;
                        data = res.data.pageData || [];
                    } else if (res.data && Array.isArray(res.data)) {
                        count = res.data.length;
                        data = res.data;
                    } else if (Array.isArray(res)) {
                        count = res.length;
                        data = res;
                    }

                    return {
                        "code": code,
                        "msg": res.msg || res.message || '',
                        "count": count,
                        "data": data
                    };
                },
                cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    { field: 'code', title: '产品编号' },
                    { field: 'name', title: '产品名称' },
                    { field: 'unit', title: '库存单位' },
                    { field: 'spec', title: '产品规格' }
                ]],
                page: true,
                limit: 30,
                limits: [30, 50, 100],
                height: 400,
                even: true,
                text: {
                    none: '无数据'
                }
            });

            // 销售订单表格事件
            table.on('tool(salesOrderTable)', function (obj) {
                var data = obj.data;
                if (obj.event === 'edit') {
                    showEditModal(data);
                }
            });

            // 销售订单表格行点击事件
            table.on('row(salesOrderTable)', function (obj) {
                var data = obj.data;
                // 显示加载提示
                var loadIndex = layui.layer.load(1, { shade: [0.1, '#fff'] });

                loadSalesOrderProducts(data.id);

                // 隐藏加载提示
                setTimeout(function () {
                    layui.layer.close(loadIndex);
                    layui.layer.msg('已加载产品明细', { icon: 1, time: 1000 });
                }, 500);
            });

            // 产品明细表格事件
            table.on('tool(productDetailTable)', function (obj) {
                var data = obj.data;
                if (obj.event === 'editQuantity') {
                    // 数量编辑功能
                } else if (obj.event === 'del') {
                    obj.del();
                }
            });

            // 全局变量
            window.currentSalesOrderId = null;
            window.productDetailTable = table;
            window.salesOrderTable = table;
            window.productSelectTable = table;
        });

        // 搜索销售订单
        function searchSalesOrder() {
            return preventDuplicateClick('searchBtn', function () {
                var orderNo = $('#searchOrderNo').val();
                layui.table.reload('salesOrderTable', {
                    where: {
                        pageIndex: 1,
                        pageSize: 10,
                        orderNo: orderNo
                    }
                });

                // 恢复按钮状态
                setTimeout(function () {
                    buttonClickStates['searchBtn'] = false;
                    $('#searchBtn').prop('disabled', false).text('查询');
                }, 1000);
            }, 1000); // 1秒超时
        }

        // 加载销售订单产品明细
        function loadSalesOrderProducts(salesOrderId) {
            window.currentSalesOrderId = salesOrderId;
            layui.table.reload('salesOrderProductTable', {
                where: {
                    salesOrderId: salesOrderId,
                    pageIndex: 1,
                    pageSize: 10
                },
                error: function (res) {
                    layui.layer.msg('加载产品明细失败: ' + (res.msg || '未知错误'));
                }
            });
        }

        // 加载编辑弹框中的产品明细
        function loadEditModalProducts(salesOrderId) {
            window.currentSalesOrderId = salesOrderId;

            // 使用AJAX直接获取数据并加载到编辑弹框的表格中
            $.ajax({
                url: '/SalesOrder/QuerySalesOrderProduct',
                type: 'GET',
                data: {
                    salesOrderId: salesOrderId,
                    pageIndex: 1,
                    pageSize: 100 // 编辑时显示更多数据
                },
                success: function (result) {
                    if (result.code === 200 && result.data && result.data.pageData) {
                        // 转换数据格式以适配编辑表格
                        var productData = result.data.pageData.map(function (item) {
                            return {
                                productCode: item.productCode,
                                productName: item.productName,
                                productSpec: item.productSpec,
                                workOrderNo: item.workOrderNo || '',
                                quantity: item.quantity,
                                createTime: item.createTime,
                                creatorName: item.creatorName
                            };
                        });

                        layui.table.reload('productDetailTable', {
                            data: productData
                        });
                    } else {
                        layui.table.reload('productDetailTable', {
                            data: []
                        });
                    }
                },
                error: function (xhr, status, error) {
                    layui.layer.msg('加载产品明细失败: ' + error);
                    layui.table.reload('productDetailTable', {
                        data: []
                    });
                }
            });
        }

        // 显示新增模态框
        function showCreateModal() {
            return preventDuplicateClick('newBtn', function () {
                $('#orderNo').val('');
                $('#remark').val('');
                layui.table.reload('productDetailTable', {
                    data: []
                });
                // 清空当前编辑的销售订单ID
                window.currentSalesOrderId = null;
                window.salesOrderLayerIndex = layui.layer.open({
                    type: 1,
                    title: '销售订单(新建)',
                    area: ['70%', '65%'],
                    content: $('#salesOrderModal'),
                    shade: 0,
                    shadeClose: false,
                    maxmin: true,
                    zIndex: 19891020,
                    success: function (layero) {
                        layui.layer.setTop(layero);
                        $(layero).css('z-index', '19891020');
                    }
                });

                // 恢复按钮状态
                setTimeout(function () {
                    buttonClickStates['newBtn'] = false;
                    $('#newBtn').prop('disabled', false).text('+新建');
                }, 1000);
            }, 1000); // 1秒超时
        }

        // 显示编辑模态框
        function showEditModal(data) {
            $('#orderNo').val(data.orderNo);
            $('#remark').val(data.remark);

            // 加载编辑弹框中的产品明细
            loadEditModalProducts(data.id);

            window.salesOrderLayerIndex = layui.layer.open({
                type: 1,
                title: '销售订单(编辑)',
                area: ['70%', '65%'],
                content: $('#salesOrderModal'),
                shade: 0,
                shadeClose: false,
                maxmin: true,
                zIndex: 19891020,
                success: function (layero) {
                    layui.layer.setTop(layero);
                    $(layero).css('z-index', '19891020');
                }
            });
        }

        // 显示产品选择模态框
        function showProductSelectModal() {
            return preventDuplicateClick('selectProductBtn', function () {
                window.productSelectLayerIndex = layui.layer.open({
                    type: 1,
                    title: '选择产品',
                    area: ['60%', '60%'],
                    content: $('#productSelectModal'),
                    shade: 0,
                    shadeClose: false,
                    maxmin: true,
                    zIndex: 19891021,
                    success: function (layero) {
                        layui.layer.setTop(layero);
                        // 强制设置层级
                        $(layero).css('z-index', '19891021');
                    }
                });

                // 恢复按钮状态
                setTimeout(function () {
                    buttonClickStates['selectProductBtn'] = false;
                    $('#selectProductBtn').prop('disabled', false).text('+选择产品');
                }, 1000);
            }, 1000); // 1秒超时
        }

        // 搜索产品
        function searchProducts() {
            return preventDuplicateClick('searchProductsBtn', function () {
                var productCode = $('#searchProductCode').val();
                var productName = $('#searchProductName').val();
                layui.table.reload('productSelectTable', {
                    where: {
                        pageIndex: 1,
                        pageSize: 30,
                        productCode: productCode,
                        productName: productName
                    }
                });

                // 恢复按钮状态
                setTimeout(function () {
                    buttonClickStates['searchProductsBtn'] = false;
                    $('#searchProductsBtn').prop('disabled', false).text('搜索');
                }, 1000);
            }, 1000); // 1秒超时
        }

        // 添加选中的产品
        function addSelectedProducts() {
            return preventDuplicateClick('addSelectedProductsBtn', function () {
                var checkStatus = layui.table.checkStatus('productSelectTable');
                var data = checkStatus.data;
                if (data.length === 0) {
                    layui.layer.msg('请选择产品');
                    return;
                }

                var currentData = layui.table.cache.productDetailTable || [];
                data.forEach(function (item) {
                    currentData.push({
                        productCode: item.code,
                        productName: item.name,
                        productSpec: item.spec,
                        workOrderNo: '',
                        quantity: 1,
                        createTime: new Date().toLocaleString(),
                        creatorName: '超级管理员'
                    });
                });

                layui.table.reload('productDetailTable', {
                    data: currentData
                });

                closeProductSelectModal();

                // 恢复按钮状态
                setTimeout(function () {
                    buttonClickStates['addSelectedProductsBtn'] = false;
                    $('#addSelectedProductsBtn').prop('disabled', false).text('添加选择的数据');
                }, 1000);
            }, 1000); // 1秒超时
        }

        // 删除产品行
        function deleteProductRow() {
            return preventDuplicateClick('deleteProductRowBtn', function () {
                var checkStatus = layui.table.checkStatus('productDetailTable');
                var data = checkStatus.data;
                if (data.length === 0) {
                    layui.layer.msg('请选择要删除的产品');
                    return;
                }

                layui.layer.confirm('确定要删除选中的产品吗？', function (index) {
                    // 获取当前表格数据
                    var tableData = [];
                    var tableCache = layui.table.cache.productDetailTable;

                    if (tableCache && tableCache.length > 0) {
                        // 过滤掉空对象
                        tableData = tableCache.filter(function (item) {
                            return item && item.productCode && item.productName;
                        });
                    }

                    // 获取选中行的索引
                    var selectedIndexes = [];
                    data.forEach(function (selectedItem) {
                        // 在表格数据中找到对应的索引
                        var rowIndex = tableData.findIndex(function (item) {
                            return item.productCode === selectedItem.productCode &&
                                item.productName === selectedItem.productName &&
                                item.quantity === selectedItem.quantity;
                        });
                        if (rowIndex !== -1) {
                            selectedIndexes.push(rowIndex);
                        }
                    });

                    // 按索引从大到小排序，避免删除时索引变化
                    selectedIndexes.sort(function (a, b) {
                        return b - a;
                    });

                    // 根据索引删除行
                    selectedIndexes.forEach(function (rowIndex) {
                        if (rowIndex >= 0 && rowIndex < tableData.length) {
                            tableData.splice(rowIndex, 1);
                        }
                    });

                    // 重新加载表格
                    layui.table.reload('productDetailTable', {
                        data: tableData
                    });

                    layui.layer.close(index);
                    layui.layer.msg('删除成功', { icon: 1, time: 1000 });

                    // 恢复按钮状态
                    buttonClickStates['deleteProductRowBtn'] = false;
                    $('#deleteProductRowBtn').prop('disabled', false).text('删除行');
                });
            }, 3000); // 3秒超时
        }

        // 保存销售订单
        function saveSalesOrder() {
            return preventDuplicateClick('saveSalesOrderBtn', function () {
                var orderNo = $('#orderNo').val();
                var remark = $('#remark').val();
                var products = layui.table.cache.productDetailTable || [];

                if (products.length === 0) {
                    layui.layer.msg('请至少添加一个产品');
                    return;
                }

                // 判断是新增还是编辑
                var isEdit = window.currentSalesOrderId !== null && window.currentSalesOrderId !== undefined;
                var url = isEdit ? '/SalesOrder/UpdateSalesOrder' : '/SalesOrder/AddSalesOrder';

                var requestData = {
                    orderNo: orderNo,
                    remark: remark,
                    products: products
                };

                // 如果是编辑，添加ID
                if (isEdit) {
                    requestData.id = window.currentSalesOrderId;
                }

                $.ajax({
                    url: url,
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(requestData),
                    success: function (result) {
                        // 恢复按钮状态
                        buttonClickStates['saveSalesOrderBtn'] = false;
                        $('#saveSalesOrderBtn').prop('disabled', false).text('保存');

                        if (result.code === 200) {
                            layui.layer.msg(isEdit ? '更新成功' : '保存成功');
                            closeSalesOrderModal();
                            // 刷新上方销售订单列表（保持当前分页与查询条件）
                            layui.table.reload('salesOrderTable', { where: { t: Date.now() } });
                            // 如果刚才是编辑，刷新下方对应的产品明细；如果是新增则清空明细区域
                            if (isEdit && window.currentSalesOrderId) {
                                loadSalesOrderProducts(window.currentSalesOrderId);
                            } else {
                                layui.table.reload('salesOrderProductTable', {
                                    where: { salesOrderId: 0, pageIndex: 1, pageSize: 10 }
                                });
                            }
                            // 清空当前编辑的销售订单ID
                            window.currentSalesOrderId = null;
                        } else {
                            layui.layer.msg(result.msg || (isEdit ? '更新失败' : '保存失败'));
                        }
                    },
                    error: function (xhr, status, error) {
                        // 恢复按钮状态
                        buttonClickStates['saveSalesOrderBtn'] = false;
                        $('#saveSalesOrderBtn').prop('disabled', false).text('保存');
                        layui.layer.msg((isEdit ? '更新失败' : '保存失败') + ': ' + error);
                    }
                });
            }, 5000); // 5秒超时
        }

        // 关闭销售订单模态框
        function closeSalesOrderModal() {
            if (window.salesOrderLayerIndex !== undefined) {
                layui.layer.close(window.salesOrderLayerIndex);
                window.salesOrderLayerIndex = undefined;
            }
        }

        // 关闭产品选择模态框
        function closeProductSelectModal() {
            if (window.productSelectLayerIndex !== undefined) {
                layui.layer.close(window.productSelectLayerIndex);
                window.productSelectLayerIndex = undefined;
            }
        }

        // 其他功能函数
        function editSelected() {
            return preventDuplicateClick('editBtn', function () {
                var checkStatus = layui.table.checkStatus('salesOrderTable');
                var data = checkStatus.data;
                if (data.length !== 1) {
                    layui.layer.msg('请选择一个销售订单进行编辑');
                    return;
                }
                showEditModal(data[0]);

                // 恢复按钮状态
                setTimeout(function () {
                    buttonClickStates['editBtn'] = false;
                    $('#editBtn').prop('disabled', false).text('编辑');
                }, 1000);
            }, 1000); // 1秒超时
        }



        function deleteSelected() {
            return preventDuplicateClick('deleteBtn', function () {
                var checkStatus = layui.table.checkStatus('salesOrderTable');
                var data = checkStatus.data;
                if (data.length === 0) {
                    layui.layer.msg('请选择要删除的销售订单');
                    return;
                }

                // 显示确认对话框
                layui.layer.confirm('确定要删除选中的 ' + data.length + ' 个销售订单吗？删除后将无法恢复！', {
                    icon: 3,
                    title: '确认删除',
                    btn: ['确定删除', '取消']
                }, function (index) {
                    // 显示加载提示
                    var loadIndex = layui.layer.load(1, { shade: [0.1, '#fff'] });

                    // 获取选中的ID列表
                    var ids = data.map(function (item) { return item.id; });

                    // 发送删除请求
                    $.ajax({
                        url: '/SalesOrder/DeleteSalesOrder',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({ ids: ids }),
                        success: function (result) {
                            layui.layer.close(loadIndex);
                            // 恢复按钮状态
                            buttonClickStates['deleteBtn'] = false;
                            $('#deleteBtn').prop('disabled', false).text('删除');

                            if (result.code === 200) {
                                layui.layer.msg(result.msg || '删除成功', { icon: 1, time: 2000 });
                                // 刷新销售订单列表
                                layui.table.reload('salesOrderTable', { where: { t: Date.now() } });
                                // 清空产品明细表格
                                layui.table.reload('salesOrderProductTable', {
                                    where: { salesOrderId: 0, pageIndex: 1, pageSize: 10 }
                                });
                                // 清空当前选中的销售订单ID
                                window.currentSalesOrderId = null;
                            } else {
                                layui.layer.msg(result.msg || '删除失败', { icon: 2, time: 3000 });
                            }
                        },
                        error: function (xhr, status, error) {
                            layui.layer.close(loadIndex);
                            // 恢复按钮状态
                            buttonClickStates['deleteBtn'] = false;
                            $('#deleteBtn').prop('disabled', false).text('删除');
                            layui.layer.msg('删除失败: ' + error, { icon: 2, time: 3000 });
                        }
                    });

                    layui.layer.close(index);
                });
            }, 5000); // 5秒超时
        }

        function printSelected() {
            return preventDuplicateClick('printBtn', function () {
                var checkStatus = layui.table.checkStatus('salesOrderTable');
                var data = checkStatus.data;
                if (data.length !== 1) {
                    layui.layer.msg('请选择一个销售订单进行打印');
                    return;
                }
                // 这里实现打印逻辑
                window.open('/SalesOrder/Print?id=' + data[0].id, '_blank');

                // 恢复按钮状态
                setTimeout(function () {
                    buttonClickStates['printBtn'] = false;
                    $('#printBtn').prop('disabled', false).text('打印');
                }, 1000);
            }, 1000); // 1秒超时
        }

        function exportData() {
            return preventDuplicateClick('exportBtn', function () {
                // 获取搜索条件
                var orderNo = $('#searchOrderNo').val();

                // 显示加载提示
                var loadIndex = layui.layer.load(2, { time: 60 * 1000 }); // 1分钟超时

                $.ajax({
                    url: '/SalesOrder/ExportSalesOrder',
                    type: 'GET',
                    data: {
                        orderNo: orderNo,
                        remark: null,
                        includeProductDetails: true
                    },
                    xhrFields: {
                        responseType: 'blob' // 接收二进制数据
                    },
                    success: function (blob, status, xhr) {
                        layui.layer.close(loadIndex);
                        // 恢复按钮状态
                        buttonClickStates['exportBtn'] = false;
                        $('#exportBtn').prop('disabled', false).text('导出');

                        // 生成带时间戳的文件名
                        var now = new Date();
                        var timestamp = now.getFullYear() +
                            String(now.getMonth() + 1).padStart(2, '0') +
                            String(now.getDate()).padStart(2, '0') +
                            String(now.getHours()).padStart(2, '0') +
                            String(now.getMinutes()).padStart(2, '0') +
                            String(now.getSeconds()).padStart(2, '0');
                        var filename = "销售订单_" + timestamp + ".xlsx";

                        // 创建下载链接
                        var url = window.URL.createObjectURL(blob);
                        var a = document.createElement('a');
                        a.href = url;
                        a.download = filename;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        window.URL.revokeObjectURL(url);
                        layui.layer.msg('导出成功，文件名：' + filename, { icon: 1 });
                    },
                    error: function (xhr, status, error) {
                        layui.layer.close(loadIndex);
                        // 恢复按钮状态
                        buttonClickStates['exportBtn'] = false;
                        $('#exportBtn').prop('disabled', false).text('导出');

                        var reader = new FileReader();
                        reader.onload = function () {
                            try {
                                var errorResponse = JSON.parse(reader.result);
                                layui.layer.alert('导出失败：' + (errorResponse.msg || '未知错误'), { icon: 2 });
                            } catch (e) {
                                layui.layer.alert('导出失败：无法解析错误信息', { icon: 2 });
                            }
                        };
                        reader.readAsText(xhr.response);
                    }
                });
            }, 60000); // 60秒超时（导出可能需要更长时间）
        }



        function refreshProductTable() {
            return preventDuplicateClick('refreshProductBtn', function () {
                layui.table.reload('productDetailTable');

                // 恢复按钮状态
                setTimeout(function () {
                    buttonClickStates['refreshProductBtn'] = false;
                    $('#refreshProductBtn').prop('disabled', false).text('刷新');
                }, 1000);
            }, 1000); // 1秒超时
        }

        // 强制表格自适应
        function forceTableAdaptive() {
            setTimeout(function () {
                // 重新渲染所有表格
                layui.table.reload('salesOrderTable');
                layui.table.reload('salesOrderProductTable');
                layui.table.reload('productDetailTable');
                layui.table.reload('productSelectTable');

                // 强制表格容器自适应
                $('.layui-table-view').each(function () {
                    $(this).css('width', '100%');
                });

                // 强制表格自适应
                $('.layui-table').each(function () {
                    $(this).css('width', '100%');
                    $(this).css('table-layout', 'auto');
                });
            }, 100);
        }

        // 页面加载完成后强制自适应
        $(document).ready(function () {
            // 页面加载完成后的初始化
            forceTableAdaptive();

            // 初始化按钮状态
            resetAllButtonStates();

            // 页面卸载时清理按钮状态
            $(window).on('beforeunload', function () {
                resetAllButtonStates();
            });

            // 加载保存的列设置
            loadSavedColumnSettings();

            // 应用列设置到表格
            setTimeout(function () {
                reloadTableWithColumnSettings();
            }, 100);
        });

        // 显示列设置弹窗
        function showColumnSettings() {
            return preventDuplicateClick('columnSettingsBtn', function () {
                updateCheckboxStates();
                updateColumnOrder();

                layui.layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 1,
                    shade: 0,
                    shadeClose: false,
                    area: ['500px', '450px'],
                    content: $('#columnSettingsModal'),
                    success: function (layero, index) {
                        layui.form.render();
                        bindColumnSettingsEvents(index);
                        initDragAndDrop();
                    }
                });

                // 恢复按钮状态
                setTimeout(function () {
                    buttonClickStates['columnSettingsBtn'] = false;
                    $('#columnSettingsBtn').prop('disabled', false).text('显示列设置');
                }, 1000);
            }, 1000);
        }

        // 更新复选框状态
        function updateCheckboxStates() {
            $('#columnSettingsTable input[type="checkbox"]').each(function () {
                var field = $(this).attr('name');
                $(this).prop('checked', columnSettings[field].visible);
            });
        }

        // 更新列顺序显示
        function updateColumnOrder() {
            var sortedFields = Object.keys(columnSettings).sort(function (a, b) {
                return columnSettings[a].order - columnSettings[b].order;
            });

            var tbody = $('#columnSettingsBody');
            tbody.empty();

            sortedFields.forEach(function (field, index) {
                var setting = columnSettings[field];
                var row = `
                                                                                                    <tr data-field="${field}" class="draggable-row">
                                                                                                        <td>${index + 1}</td>
                                                                                                        <td class="drag-handle" style="cursor: move;">
                                                                                                            <i class="layui-icon layui-icon-drag" style="margin-right: 8px; color: #999;"></i>
                                                                                                            ${getColumnTitle(field)}
                                                                                                        </td>
                                                                                                        <td><input type="checkbox" name="${field}" lay-skin="primary" title="显示" ${setting.visible ? 'checked' : ''}></td>
                                                                                                    </tr>
                                                                                                `;
                tbody.append(row);
            });
        }

        // 获取列标题
        function getColumnTitle(field) {
            var titles = {
                'orderNo': '单据编号',
                'remark': '备注',
                'createTime': '创建时间',
                'creatorName': '创建人',
                'modifyTime': '修改时间',
                'modifierName': '修改人'
            };
            return titles[field] || field;
        }

        // 初始化拖拽功能
        function initDragAndDrop() {
            $('#columnSettingsBody').sortable({
                handle: '.drag-handle',
                axis: 'y',
                opacity: 0.8,
                tolerance: 'pointer',
                helper: function (e, tr) {
                    var $originals = tr.children();
                    var $helper = tr.clone();
                    $helper.children().each(function (index) {
                        $(this).width($originals.eq(index).width());
                    });
                    return $helper;
                },
                update: function (event, ui) {
                    updateColumnOrderAfterDrag();
                }
            });
        }

        // 拖拽后更新列顺序
        function updateColumnOrderAfterDrag() {
            $('#columnSettingsBody tr').each(function (index) {
                var field = $(this).data('field');
                if (field && columnSettings[field]) {
                    columnSettings[field].order = index + 1;
                }
                $(this).find('td:first').text(index + 1);
            });
        }

        // 绑定列设置事件
        function bindColumnSettingsEvents(layerIndex) {
            $('#cancelColumnSettings').off('click').on('click', function () {
                layui.layer.close(layerIndex);
            });

            $('#resetColumnSettings').off('click').on('click', function () {
                columnSettings = {
                    orderNo: { visible: true, order: 1 },
                    remark: { visible: true, order: 2 },
                    createTime: { visible: true, order: 3 },
                    creatorName: { visible: true, order: 4 },
                    modifyTime: { visible: true, order: 5 },
                    modifierName: { visible: true, order: 6 }
                };
                updateCheckboxStates();
                updateColumnOrder();
                layui.form.render();
            });

            $('#confirmColumnSettings').off('click').on('click', function () {
                // 更新可见性设置
                $('#columnSettingsTable input[type="checkbox"]').each(function () {
                    var field = $(this).attr('name');
                    if (columnSettings[field]) {
                        columnSettings[field].visible = $(this).prop('checked');
                    }
                });

                // 保存设置到localStorage
                localStorage.setItem('salesOrderColumnSettings', JSON.stringify(columnSettings));

                reloadTableWithColumnSettings();
                layui.layer.close(layerIndex);
                layui.layer.msg('列设置已更新', { icon: 1 });
            });
        }

        // 根据列设置重新渲染表格
        function reloadTableWithColumnSettings() {
            layui.table.reload('salesOrderTable', {
                cols: [getSalesOrderTableCols()]
            });
        }

        // 加载保存的列设置
        function loadSavedColumnSettings() {
            var savedSettings = localStorage.getItem('salesOrderColumnSettings');
            if (savedSettings) {
                try {
                    var saved = JSON.parse(savedSettings);
                    // 合并保存的设置，保持默认值作为后备
                    Object.keys(saved).forEach(function (field) {
                        if (columnSettings[field]) {
                            columnSettings[field].visible = saved[field].visible !== undefined ? saved[field].visible : columnSettings[field].visible;
                            columnSettings[field].order = saved[field].order !== undefined ? saved[field].order : columnSettings[field].order;
                        }
                    });
                } catch (error) {
                    console.error('加载列设置失败:', error);
                }
            }
        }

        // 获取销售订单表格列配置
        function getSalesOrderTableCols() {
            var cols = [
                { type: 'checkbox', fixed: 'left' }
            ];

            // 按顺序添加可见的列
            var sortedFields = Object.keys(columnSettings).sort(function (a, b) {
                return columnSettings[a].order - columnSettings[b].order;
            });

            sortedFields.forEach(function (field) {
                if (columnSettings[field].visible && columnConfigs[field]) {
                    cols.push(columnConfigs[field]);
                }
            });

            return cols;
        }

        // 窗口大小改变时重新自适应
        $(window).resize(function () {
            forceTableAdaptive();
        });
    </script>
}
